/// 🎯 活动发布表单模型
/// 
/// 用于管理活动发布页面的表单数据、验证和变更检测
/// 符合企业级 Form 模型标准
class ActivityPublishForm {
  // ==================== 表单字段 ====================
  
  /// 活动标题
  String title = '';
  
  /// 活动详情
  String details = '';
  
  /// 参与人数
  String peopleCount = '';
  
  /// 地点描述
  String location = '';
  
  /// 活动纬度
  double latitude = 0.0;
  
  /// 活动经度
  double longitude = 0.0;
  
  /// 开始时间
  DateTime? startDate;
  
  /// 结束时间
  DateTime? endDate;
  
  /// 限制选项（无限制/男/女）
  String selectedLimit = '无限制';
  
  /// 消费方式（我买单/AA/双方商议）
  String selectedPayment = '我买单';
  
  /// 活动图片列表（最多4张）
  List<String> activityImages = [];
  
  /// 是否为默认位置
  bool isDefaultLocation = true;
  
  // ==================== 构造函数 ====================
  
  ActivityPublishForm();
  
  // ==================== 表单验证 ====================
  
  /// 验证活动标题
  String? validateTitle() {
    if (title.trim().isEmpty) {
      return '请输入活动标题';
    }
    if (title.trim().length < 2) {
      return '活动标题至少2个字符';
    }
    if (title.trim().length > 50) {
      return '活动标题最多50个字符';
    }
    return null;
  }
  
  /// 验证活动详情
  String? validateDetails() {
    if (details.trim().isEmpty) {
      return '请输入活动详情';
    }
    if (details.trim().length < 10) {
      return '活动详情至少10个字符';
    }
    if (details.trim().length > 150) {
      return '活动详情最多150个字符';
    }
    return null;
  }
  
  /// 验证参与人数
  String? validatePeopleCount() {
    if (peopleCount.trim().isEmpty) {
      return '请输入参与人数';
    }
    
    final count = int.tryParse(peopleCount.trim());
    if (count == null) {
      return '请输入有效的数字';
    }
    
    if (count <= 0) {
      return '参与人数必须大于0';
    }
    
    if (count > 999) {
      return '参与人数不能超过999';
    }
    
    return null;
  }
  
  /// 验证开始时间
  String? validateStartDate() {
    if (startDate == null) {
      return '请选择开始时间';
    }
    
    // 检查是否在未来
    if (startDate!.isBefore(DateTime.now().subtract(const Duration(minutes: 5)))) {
      return '开始时间不能早于当前时间';
    }
    
    return null;
  }
  
  /// 验证结束时间
  String? validateEndDate() {
    if (endDate == null) {
      return '请选择结束时间';
    }
    
    if (startDate == null) {
      return '请先选择开始时间';
    }
    
    if (endDate!.isBefore(startDate!) || endDate!.isAtSameMomentAs(startDate!)) {
      return '结束时间必须大于开始时间';
    }
    
    // 检查持续时间是否合理
    final duration = endDate!.difference(startDate!);
    final durationMinutes = duration.inMinutes;
    final durationDays = duration.inMinutes / (60 * 24);
    
    // 验证1：活动时长至少30分钟
    if (durationMinutes < 30) {
      return '活动时长至少需要30分钟';
    }
    
    // 验证2：活动时长最多7天
    if (durationDays > 7) {
      return '活动时长最多7天';
    }
    
    return null;
  }
  
  /// 验证地点
  String? validateLocation() {
    if (location.trim().isEmpty) {
      return '请选择活动地点';
    }
    return null;
  }
  
  /// 表单是否全部有效
  bool get isValid {
    return validateTitle() == null &&
           validateDetails() == null &&
           validatePeopleCount() == null &&
           validateStartDate() == null &&
           validateEndDate() == null &&
           validateLocation() == null &&
           validateImages() == null;
  }
  
  /// 获取所有验证错误
  Map<String, String> get validationErrors {
    final errors = <String, String>{};
    
    final titleError = validateTitle();
    if (titleError != null) errors['title'] = titleError;
    
    final detailsError = validateDetails();
    if (detailsError != null) errors['details'] = detailsError;
    
    final peopleCountError = validatePeopleCount();
    if (peopleCountError != null) errors['peopleCount'] = peopleCountError;
    
    final startDateError = validateStartDate();
    if (startDateError != null) errors['startDate'] = startDateError;
    
    final endDateError = validateEndDate();
    if (endDateError != null) errors['endDate'] = endDateError;
    
    final locationError = validateLocation();
    if (locationError != null) errors['location'] = locationError;

    final imageError = validateImages();
    if (imageError != null) errors['images'] = imageError;
    
    return errors;
  }

  /// 验证活动图片（至少一张已上传成功的图片）
  String? validateImages() {
    if (!hasUploadedImages) {
      return '请至少上传一张活动图片';
    }
    return null;
  }
  
  // ==================== 辅助方法 ====================
  
  /// 获取开始时间的格式化文本
  String get startDateText {
    if (startDate == null) return '';
    return _formatDateTime(startDate!);
  }
  
  /// 获取结束时间的格式化文本
  String get endDateText {
    if (endDate == null) return '';
    return _formatDateTime(endDate!);
  }
  
  /// 格式化日期时间为中文格式
  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}年${dateTime.month}月${dateTime.day}日 '
           '${dateTime.hour.toString().padLeft(2, '0')}:'
           '${dateTime.minute.toString().padLeft(2, '0')}';
  }
  
  /// 格式化日期时间为API要求的格式
  String formatDateTimeForApi(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-'
           '${dateTime.day.toString().padLeft(2, '0')} '
           '${dateTime.hour.toString().padLeft(2, '0')}:'
           '${dateTime.minute.toString().padLeft(2, '0')}:00';
  }
  
  /// 计算活动持续时间（小时）
  double calculateDuration() {
    if (startDate == null || endDate == null) return 0.0;
    
    final duration = endDate!.difference(startDate!);
    final hours = duration.inMinutes / 60.0;
    
    return double.parse(hours.toStringAsFixed(1));
  }
  
  /// 获取活动持续时间的显示文本
  String get durationDisplayText {
    if (startDate == null || endDate == null) return '未知';
    
    final duration = endDate!.difference(startDate!);
    final totalMinutes = duration.inMinutes;
    
    if (totalMinutes < 60) {
      return '${totalMinutes}分钟';
    } else if (totalMinutes < 1440) { // 24小时
      final hours = totalMinutes ~/ 60;
      final minutes = totalMinutes % 60;
      if (minutes == 0) {
        return '${hours}小时';
      } else {
        return '${hours}小时${minutes}分钟';
      }
    } else {
      final days = totalMinutes ~/ 1440;
      final remainingHours = (totalMinutes % 1440) ~/ 60;
      if (remainingHours == 0) {
        return '${days}天';
      } else {
        return '${days}天${remainingHours}小时';
      }
    }
  }
  
  /// 获取活动类型数组（包含消费方式和限制）
  List<String> get activityTypeArray {
    final types = <String>[selectedPayment];
    if (selectedLimit != '无限制') {
      types.add(selectedLimit);
    }
    return types;
  }
  
  /// 获取网络图片URL列表（过滤本地路径）
  List<String>? get networkImageUrls {
    final networkImages = activityImages
        .where((img) => img.startsWith('http'))
        .toList();
    
    return networkImages.isNotEmpty ? networkImages : null;
  }

  /// 是否已经上传至少一张图片
  bool get hasUploadedImages {
    return activityImages.any((img) => img.startsWith('http'));
  }
  
  /// 检查图片数量是否已达上限
  bool get isImageLimitReached => activityImages.length >= 4;
  
  /// 获取图片数量文本
  String get imageCountText => '(${activityImages.length}/4)';
  
  // ==================== 重置方法 ====================
  
  /// 清空表单
  void reset() {
    title = '';
    details = '';
    peopleCount = '';
    location = '';
    latitude = 0.0;
    longitude = 0.0;
    startDate = null;
    endDate = null;
    selectedLimit = '无限制';
    selectedPayment = '我买单';
    activityImages.clear();
    isDefaultLocation = true;
  }
  
  // ==================== 调试输出 ====================
  
  @override
  String toString() {
    return 'ActivityPublishForm{\n'
           '  title: $title,\n'
           '  details: $details (${details.length}字),\n'
           '  peopleCount: $peopleCount,\n'
           '  location: $location,\n'
           '  coordinates: ($latitude, $longitude),\n'
           '  startDate: $startDate,\n'
           '  endDate: $endDate,\n'
           '  duration: ${durationDisplayText},\n'
           '  selectedLimit: $selectedLimit,\n'
           '  selectedPayment: $selectedPayment,\n'
           '  images: ${activityImages.length}张,\n'
           '  isValid: $isValid\n'
           '}';
  }
}

